import { UserInfo } from '../models/UserInfo';
import { lz, request, http } from '@zny/utils';
import Cookies from 'js-cookie';
import defaultSettings from '../layouts/biz_layouts/defaultSettings';
import { setLocalStorage, getLocalStorage, setStore } from '@zny/hooks';
import { WebVariable } from './WebVariable';

/**会话信息 */
export class Session {

    private static USER_STORAGE_KEY = "userInfo"
    private static defaultSettingsRequested = false

    /**获取当前登录用户 */
    static getUser(): IUserInfo | undefined {
        const value = localStorage.getItem(this.USER_STORAGE_KEY)
        if (value == null) {
            return undefined
        }
        const user = lz(value, true)
        if (user == "") {
            return undefined
        }
        return JSON.parse(user)
    }

    static isProjectEmpty(): boolean {
        const user = this.getUser()
        if (typeof user == "undefined") {
            return true
        }
        return typeof user._LoginProjectId == "undefined"
            || user._LoginProjectId == ""
            || typeof user.projectName == "undefined"
            || user.projectName == ""
    }

    /**
     * 设置登录用户
     * @param user 服务器返回的用户信息
     * @param loginProjectId
     * @param tenantId
     * @param projectName
     */
    static setUser(user: UserInfo, loginProjectId: string, tenantId: string, projectName: string) {
        const u: IUserInfo = user as any
        u._LoginProjectId = loginProjectId
        u._TenantId = tenantId
        u.projectName = projectName
        const str = lz(JSON.stringify(u), false)
        localStorage.setItem(this.USER_STORAGE_KEY, str)
    }

    /**获取项目ID */
    static getProjectId(): string {
        return this.getUser()?._LoginProjectId ?? ""
    }

    /**
     * 设置项目ID
     * @param projectId 新的项目ID
     * @param projectName 项目名称
     */
    static setProjectId(projectId: string, projectName: string) {
        let defaultSettingsSys = getLocalStorage("globalSettings");
        defaultSettingsSys._LoginProjectId = projectId;
        defaultSettingsSys._TenantId = projectId;
        defaultSettingsSys.useAuth = WebVariable.useAuth;
        defaultSettingsSys.useAuthButton = WebVariable.useAuthButton;
        defaultSettingsSys.MapKey = WebVariable.MapKey;
        defaultSettingsSys.MapKeyTwo = WebVariable.MapKeyTwo;
        defaultSettingsSys.showGis = WebVariable.showGis;
        defaultSettingsSys.showBim = WebVariable.showBim;
        defaultSettingsSys.workflowServerAddress = WebVariable.workflowServerAddress;
        defaultSettingsSys.pageIndex = WebVariable.pageIndex;
        defaultSettingsSys.ImpPlanDownUrl = WebVariable.ImpPlanDownUrl;
        defaultSettingsSys.ManagePlanDownUrl = WebVariable.ManagePlanDownUrl;
        defaultSettingsSys.fileServerAddress = WebVariable.fileServerAddress;

        Object.keys(defaultSettingsSys).map((key: any) => {
            defaultSettings[key] = defaultSettingsSys[key];
        });

        if(projectId!=""){
            console.log(projectId,'projectId......................');
            localStorage.setItem("_loginProjectId",projectId);
        }

        sessionStorage.setItem("defaultSettings", JSON.stringify(defaultSettings));
        setLocalStorage('globalSettings', defaultSettings);
        console.log('......................................设置项目id：' + projectId);
        this.setUser(this.getUser() as any, projectId, projectId, projectName)
    }

    /**退出登录 */
    static logout() {
        setStore('BarometerSearchYear',null)
        Cookies.remove("znyToken")
        localStorage.removeItem(this.USER_STORAGE_KEY)
        let pathname = location.origin
        if (process.env.NODE_ENV == 'development') {
            // pathname = 'http://10.219.86.03:8001'
            pathname = 'http://10.219.86.138:8001'
        }
        location.replace(`${WebVariable.ssoPage}?FromUrl=${pathname}`)
        //location.replace(`http://portal.cs.msdi.cn/r1/SignOnServlet?FromUrl=${pathname}`)
    }

    static getCookie(): ICookieInfo | undefined {
        const cookieVal = Cookies.get('znyToken');
        if (typeof cookieVal != "string") {
            return undefined
        }
        const deCodeCookie = decodeURIComponent(cookieVal)
        return JSON.parse(deCodeCookie)
    }

    static getApiToken(): string {
        return this.getCookie()?.accessToken ?? ""
    }

    /**读取默认配置 */
    static async getDefaultSettings(): Promise<void> {
        if (!this.defaultSettingsRequested) {
            const res = await request(`/rjApi/data/getByKey?key=defaultSettings`)
            const settings = JSON.parse(res.value)
            Object.assign(WebVariable, settings)
            Object.assign(defaultSettings, settings)
            this.defaultSettingsRequested = true
            return Promise.resolve()
        }
        return Promise.resolve()
    }

}

export interface IUserInfo extends UserInfo {
    _LoginProjectId: string
    _TenantId: string
    projectName: string
}

export interface ICookieInfo {
    accessToken: string
    avatar?: string
    expiresIn: number
    license: string
    [key: string]: any
}
